/*******************************************************************************
 * Copyright (c) 2010, 2030 www.itlaobing.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package cn.itlaobing.web.servlet;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.itlaobing.web.annotation.MappingAnnotation;

/** 
 * ClassName: BaseServlet <br/> 
 * Function: TODO 功能描述 <br/> 
 * date: 2017年10月31日 下午9:02:40 <br/> 
 * 
 * @author 王博 
 * @version  
 * @since JDK 1.8 
 */
public class BaseServlet extends HttpServlet {

	private Map<String, Method> requestmapping = new HashMap<String, Method>();

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest,
	 * javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String urlrequest=request.getRequestURI();
		Method method=requestmapping.get(urlrequest);
		try {
			method.invoke(this,request,response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig)
	 */
	@Override
	public void init(ServletConfig config) throws ServletException {
		// 获取当前反射对象
		Class cla = this.getClass();
		// 获取当前的webservlet
		WebServlet webservlet = (WebServlet) cla.getAnnotation(WebServlet.class);
		//获取urlpatting
		String url = webservlet.value()[0];
		//通过反射获取所有的方法
		Method[] methods = cla.getDeclaredMethods();
		//遍历
		for (Method method : methods) {
			//判断方法上是否有注解
			if(method.isAnnotationPresent(MappingAnnotation.class)) {
				MappingAnnotation mappingannotation=method.getAnnotation(MappingAnnotation.class);
				String mappannotation=mappingannotation.value();
				if(!mappannotation.startsWith("/")) {
					mappannotation="/"+mappannotation;
				}
				mappannotation=url.replace("/*", "")+mappannotation;
				requestmapping.put(mappannotation, method);
			}
		}
		Set<Entry<String,Method>> enty=requestmapping.entrySet();
		Iterator<Entry<String,Method>> it=enty.iterator();
		while(it.hasNext()) {
			Entry<String,Method> en=it.next();
			//System.out.println(en.getKey()+">>"+en.getValue());
		}
	}
}
